package com.my.netty.basic.channel;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

@Slf4j
public class CloseFutureClient {

    /**
     * ChannelFuture处理关闭连接
     */
    public static void main(String[] args) throws InterruptedException {
        //ChannelFuture是connect调用后立即返回的一个对象
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
            .group(eventLoopGroup)
            .channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel sc) {
                    //这个Handler可以让netty打印调试日志，注意将logback.xml中对应的logger的level设为debug
                    sc.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                    sc.pipeline().addLast(new StringEncoder());
                }
            })
            .connect(new InetSocketAddress("localhost", 8080));

        Channel channel = channelFuture.sync().channel();
        log.info("已连接连接服务端 {}", channel);
        Scanner sc = new Scanner(System.in);
        String line;
        while (true) {
            System.out.println("输入向服务端发送的数据：");
            line = sc.nextLine();
            if ("q".equalsIgnoreCase(line)) {
                break;
            }
            channel.writeAndFlush(line);
        }
        sc.close();
        //输入q之后进行关闭的操作，close方法也是异步操作，执行后不代表已经关闭连接；真正执行close操作的是NIO线程
        channel.close();

        //获取CloseFuture
        ChannelFuture closeFuture = channel.closeFuture();
        //方法1 同步处理，sync方法阻塞等待连接关闭
//        closeFuture.sync();
//        log.info("客户端退出");

        //方法2 异步处理 addListener，连接关闭时，NIO线程执行operationComplete方法
        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                log.info("客户端退出");
                //关闭eventLoop线程池，这样JVM进程才能结束
                eventLoopGroup.shutdownGracefully();
            }
        });
    }
}
